package com.medassistent.gui;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;


import com.medassistent.gui.*;
import com.medassistent.source.*;

import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;


public class EditarPaciente extends Activity {
	
	private EditText nome;
	private EditText textRua;
	private EditText textNumero;
	private EditText textBairro;
	private EditText textCidade;
	private EditText textIdade;
	private EditText textTelefone;
	private Spinner spinner;
	private Activity atividade = this;
	private String sexo = "Feminino";
	private EditText textTelefoneResponsavel;
	private CheckBox ativarAvisoAtraso;
	private ImageButton cameraButton;
	private Paciente pacienteSelecionado;


	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_editar_paciente);
		
		long id = getIntent().getExtras().getLong("id");
		final int posicaoClicada = getIntent().getExtras().getInt("posicao");
		pacienteSelecionado = Paciente.findById(Paciente.class, id);
		
		nome = (EditText) findViewById(R.id.textNome);
		textRua = (EditText) findViewById(R.id.textRua);

		textNumero = (EditText) findViewById(R.id.textNumero);
		textBairro = (EditText) findViewById(R.id.textBairro);
		textCidade = (EditText) findViewById(R.id.textCidade);
		textIdade = (EditText) findViewById(R.id.textIdade);
		textTelefone = (EditText) findViewById(R.id.textTelefone);
		textTelefoneResponsavel = (EditText) findViewById(R.id.editTextTelefoneResponsavel);
		ativarAvisoAtraso = (CheckBox) findViewById(R.id.checkBoxAtivarAvisoAtraso);
		RadioButton bntMulher = (RadioButton) findViewById(R.id.radioButton1);
		RadioButton bntHomem = (RadioButton) findViewById(R.id.radioButton2);
		final RadioGroup grupo = (RadioGroup) findViewById(R.id.radioGroup);
		cameraButton = (ImageButton) findViewById(R.id.cameraButton);
		bntMulher.setId(0);
		bntHomem.setId(1);
		grupo.check(0);
		
		List<String> tiposSanguineos = new ArrayList<String>();
		tiposSanguineos.add("A−");
		tiposSanguineos.add("A+");
		tiposSanguineos.add("B-");
		tiposSanguineos.add("B+");
		tiposSanguineos.add("AB−");
		tiposSanguineos.add("AB+");
		tiposSanguineos.add("O−");
		tiposSanguineos.add("O+");
		
		final Spinner spinner = (Spinner) findViewById(R.id.spinner1);
		
		final Spinner spinnerMinutosAtraso = (Spinner) findViewById(R.id.spinnerMinutosAtraso);
		List<Integer> listaMinutosAtraso= new ArrayList<Integer>();
		listaMinutosAtraso.add(5);
		listaMinutosAtraso.add(10);
		listaMinutosAtraso.add(15);
		listaMinutosAtraso.add(20);
		listaMinutosAtraso.add(25);
		listaMinutosAtraso.add(30);
		final ArrayAdapter<Integer> arrayAdapterMinutosAtraso = new ArrayAdapter<Integer>(
				this, android.R.layout.simple_spinner_dropdown_item, listaMinutosAtraso);
		spinnerMinutosAtraso.setAdapter(arrayAdapterMinutosAtraso);
		
		nome.setText(pacienteSelecionado.getNome());
		textIdade.setText(pacienteSelecionado.getIdade());
		textRua.setText(pacienteSelecionado.getEndereco().getRua());
		textNumero.setText(pacienteSelecionado.getEndereco().getNumero());
		textBairro.setText(pacienteSelecionado.getEndereco().getBairro());
		textCidade.setText(pacienteSelecionado.getEndereco().getCidade());
		textTelefone.setText(pacienteSelecionado.getTelefone());
		textTelefoneResponsavel.setText(pacienteSelecionado.getTelefoneResponsavel());
		ativarAvisoAtraso.setChecked(pacienteSelecionado.isAvisarAtraso());
		
		
		ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, tiposSanguineos);
		ArrayAdapter<String> spinnerArrayAdapter = arrayAdapter;
		spinner.setAdapter(spinnerArrayAdapter);
		
		
		if(pacienteSelecionado.getSexo().equalsIgnoreCase("feminino")){
			grupo.check(0);
		}
		else{
			grupo.check(1);
		}
		
		if(pacienteSelecionado.getTipoSanguineo().equalsIgnoreCase("A-")){
			spinner.setSelection(0);
		}
		if(pacienteSelecionado.getTipoSanguineo().equalsIgnoreCase("A+")){
			spinner.setSelection(1);
		}
		if(pacienteSelecionado.getTipoSanguineo().equalsIgnoreCase("B-")){
			spinner.setSelection(2);
			
		}
		if(pacienteSelecionado.getTipoSanguineo().equalsIgnoreCase("B+")){
			spinner.setSelection(3);
		}
		if(pacienteSelecionado.getTipoSanguineo().equalsIgnoreCase("AB-")){
			spinner.setSelection(4);
		}
		if(pacienteSelecionado.getTipoSanguineo().equalsIgnoreCase("AB+")){
			spinner.setSelection(5);
		}
		if(pacienteSelecionado.getTipoSanguineo().equalsIgnoreCase("O-")){
			spinner.setSelection(6);
		}
		if(pacienteSelecionado.getTipoSanguineo().equalsIgnoreCase("O+")){
			spinner.setSelection(7);
		}
		
		BitmapFactory.Options options = new BitmapFactory.Options();
        options.inPreferredConfig = Bitmap.Config.ARGB_8888;
        String photoPath = Environment.getExternalStorageDirectory().toString() + File.separator + "0" + id + ".png";
        Bitmap bitmap = BitmapFactory.decodeFile(photoPath, options);
        cameraButton.setImageBitmap(bitmap);
		
		
		cameraButton.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				selectImage();
				
			}
		});
		
		
		Button bntEditar = (Button) findViewById(R.id.botaoSalvarEdicao);
		Button bntGPS = (Button) findViewById(R.id.gps2);
		
		bntGPS.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				LocationManager locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
				if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)){
					LocationListener locationListener = new LocationListener() {
						public void onLocationChanged(Location location) {
							double latitude = location.getLatitude();
							double longitude = location.getLongitude();
						}

						public void onStatusChanged(String provider, int status, Bundle extras) {}
						public void onProviderEnabled(String provider) {}
						public void onProviderDisabled(String provider) {}
					};
					
					locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);

					Geocoder geocoder = new Geocoder(getBaseContext(), Locale.ENGLISH);
					String ret;
					String novaRua="";
					String novaCidade="";
					String novoNumero="";
					String novoBairro="";
					try {
						List<Address> addresses = geocoder.getFromLocation
								(locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER).getLatitude(), 
										locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER).getLongitude(), 1);
						if(addresses != null) {
							Address returnedAddress = addresses.get(0);
							novaRua = returnedAddress.getThoroughfare();
							novaCidade = returnedAddress.getLocality();
							novoNumero = returnedAddress.getSubThoroughfare();
							novoBairro = returnedAddress.getSubLocality();
						}
						else{
							ret = "Endereço não encontrado.";
							textRua.setText(ret);
							textCidade.setText(ret);
							textNumero.setText(ret);
							textBairro.setText(ret);
						}
					} catch (IOException e) {
						e.printStackTrace();
						ret = "Serviço indisponível!";
						textRua.setText(ret);
						textIdade.setText(ret);
						textNumero.setText(ret);
						textBairro.setText(ret);
					}
					textRua.setText(novaRua);
					textCidade.setText(novaCidade);
					textNumero.setText(novoNumero);
					textBairro.setText(novoBairro);
				}
				else{
					new AlertDialog.Builder(EditarPaciente.this)
					.setTitle("Serviço indisponível!")
					.setMessage("Tente novamente.").show();
		

				}
			}});
		
		bntEditar.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {

				if (nome.getText().toString().isEmpty()) {

					new AlertDialog.Builder(EditarPaciente.this)
					.setTitle("Edição inválida!")
					.setMessage("O paciente deve ter um nome").show();
				} else {
					if (ativarAvisoAtraso.isChecked() && textTelefoneResponsavel.getText().toString().length() < 10) {
						new AlertDialog.Builder(EditarPaciente.this)
						.setTitle("Aviso")
						.setMessage("O número do responsável precisa ter no mínimo 10 digitos DDD xxxx-xxxx")
						.show();
				
				}else{
					pacienteSelecionado.setNome(nome.getText().toString());
				//	int idadeReal = Integer.parseInt(idade.getText().toString());
					pacienteSelecionado.setIdade(textIdade.getText().toString());
					pacienteSelecionado.setTipoSanguineo(spinner.getSelectedItem().toString());
					pacienteSelecionado.setTelefone(textTelefone.getText().toString());
					pacienteSelecionado.getEndereco().setRua(textRua.getText().toString());
				//	int numeroReal = Integer.parseInt(numero.getText().toString());
					pacienteSelecionado.getEndereco().setNumero(textNumero.getText().toString());
					pacienteSelecionado.getEndereco().setBairro(textBairro.getText().toString());
					pacienteSelecionado.getEndereco().setCidade(textCidade.getText().toString());
					pacienteSelecionado.setTelefoneResponsavel(textTelefoneResponsavel.getText().toString());
					pacienteSelecionado.setAvisarAtraso(ativarAvisoAtraso.isChecked());
					pacienteSelecionado.setToleranciaAtraso(Integer.parseInt(spinnerMinutosAtraso.getItemAtPosition(spinnerMinutosAtraso.getSelectedItemPosition()).toString()));
					if (ativarAvisoAtraso.isChecked()) {
						if (textTelefoneResponsavel.getText().toString().length() < 10) {
							new AlertDialog.Builder(EditarPaciente.this)
							.setTitle("Aviso")
							.setMessage("O número do responsável precisa ter no mínimo 10 digitos DDD xxxx-xxxx")
							.show();
						}
					}
					if(grupo.getCheckedRadioButtonId() == 0){
						pacienteSelecionado.setSexo("Feminino");
					}
					
					else{
						pacienteSelecionado.setSexo("Masculino");
					}
					
					TelaPacientes.listaDePacientes.remove(posicaoClicada);
					TelaPacientes.listaDePacientes.add(posicaoClicada, pacienteSelecionado);
					pacienteSelecionado.getEndereco().save();
					pacienteSelecionado.save();
					
					BitmapDrawable drawable = (BitmapDrawable) cameraButton.getDrawable();
					Bitmap bitmap = drawable.getBitmap();
					savebitmap(bitmap, "" + pacienteSelecionado.getId());
					
					TelaPacientes.atualizaPacientes();
					

					new AlertDialog.Builder(EditarPaciente.this)
					.setTitle("Edição")
					.setMessage("Informações atualizadas!").show();
					
					new Handler().postDelayed(new Runnable() {
				        @Override
				        public void run() {
				            atividade.finish();
				        }
				    }, 2000);
					
				}

				}


			}

		});
		
	}

	private File savebitmap(Bitmap bmp, String idFileName) {
	      String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
	      OutputStream outStream = null;
	     // String temp = null;
	      
	    	idFileName = "0" + idFileName;
	        File file = new File(extStorageDirectory, idFileName + ".png");
	      if (file.exists()) {
	       file.delete();
	       file = new File(extStorageDirectory, idFileName + ".png");

	      }

	      try {
	       outStream = new FileOutputStream(file);
	       bmp.compress(Bitmap.CompressFormat.PNG, 100, outStream);
	       outStream.flush();
	       outStream.close();

	      } catch (Exception e) {
	       e.printStackTrace();
	       return null;
	      }
	      return file;
	     }
	    @Override
	    public boolean onCreateOptionsMenu(Menu menu) {
	        // Inflate the menu; this adds items to the action bar if it is present.
	        getMenuInflater().inflate(R.menu.main, menu);
	        return true;
	    }
	    
	    private void selectImage() {

	            final CharSequence[] options = { "Tirar foto", "Escolher da galeria","Cancelar" };



	            AlertDialog.Builder builder = new AlertDialog.Builder(EditarPaciente.this);

	            builder.setTitle("Adicionar foto!");

	            builder.setItems(options, new DialogInterface.OnClickListener() {

	                @Override

	                public void onClick(DialogInterface dialog, int item) {

	                    if (options[item].equals("Tirar foto")){

	                        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

	                        File f = new File(android.os.Environment.getExternalStorageDirectory(), "temp.jpg");

	                        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
	                        //pic = f;

	                        startActivityForResult(intent, 1);


	                    }

	                    else if (options[item].equals("Escolher da galeria"))

	                    {

	                        Intent intent = new   Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

	                        startActivityForResult(intent, 2);



	                    }

	                    else if (options[item].equals("Cancelar")) {

	                        dialog.dismiss();

	                    }

	                }

	            });

	            builder.show();

	        }



	        @Override

	        protected void onActivityResult(int requestCode, int resultCode, Intent data) {

	            super.onActivityResult(requestCode, resultCode, data);

	            if (resultCode == RESULT_OK) {

	                if (requestCode == 1) {
	                    //h=0;
	                    File f = new File(Environment.getExternalStorageDirectory().toString());

	                    for (File temp : f.listFiles()) {

	                        if (temp.getName().equals("temp.jpg")) {

	                            f = temp;
	                            File photo = new File(Environment.getExternalStorageDirectory(), "temp.jpg");
	                           //pic = photo;
	                            break;

	                        }

	                    }

	                    try {
	                    	
	                    	cropCapturedImage(Uri.fromFile(f));

	                        Bitmap bitmap;

	                        BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();



	                        bitmap = BitmapFactory.decodeFile(f.getAbsolutePath(),

	                                bitmapOptions); 



	                        //cameraButton.setImageBitmap(bitmap);




	                        String path = android.os.Environment

	                                .getExternalStorageDirectory()

	                                + File.separator

	                                + "Phoenix" + File.separator + "default";
	                        //p = path;
	                        
	                        


	                        OutputStream outFile = null;

	                        File file = new File(path, String.valueOf(System.currentTimeMillis()) + ".jpg");

	                        try {

	                            outFile = new FileOutputStream(file);

	                            bitmap.compress(Bitmap.CompressFormat.JPEG, 85, outFile);
	                            
	                            
	    //pic=file;
	                            outFile.flush();

	                            outFile.close();


	                        } catch (FileNotFoundException e) {

	                            e.printStackTrace();

	                        } catch (IOException e) {

	                            e.printStackTrace();

	                        } catch (Exception e) {

	                            e.printStackTrace();

	                        }

	                    } catch (Exception e) {

	                        e.printStackTrace();

	                    }

	                } else if (requestCode == 2) {



	                    Uri selectedImage = data.getData();
	                   // h=1;
	    //imgui = selectedImage;
	                    String[] filePath = { MediaStore.Images.Media.DATA };

	                    Cursor c = getContentResolver().query(selectedImage,filePath, null, null, null);

	                    c.moveToFirst();

	                    int columnIndex = c.getColumnIndex(filePath[0]);

	                    String picturePath = c.getString(columnIndex);

	                    c.close();
	                    
	                    File f = new File(picturePath);
	                    cropCapturedImage(Uri.fromFile(f));
	                    

	                    Log.w("path of image from gallery......******************.........", picturePath+"");

	                }
	                else if(requestCode == 3){
	                	
	                	
	                	Bundle extras = data.getExtras();
	        			//get the cropped bitmap from extras
	        			Bitmap thePic = extras.getParcelable("data");
	        			//set image bitmap to image view
	        			cameraButton.setImageBitmap(thePic);
	                }

	            }
	        }
	        
	        public void cropCapturedImage(Uri picUri){
	    		//call the standard crop action intent 
	    		Intent cropIntent = new Intent("com.android.camera.action.CROP");
	    		//indicate image type and Uri of image
	    		cropIntent.setDataAndType(picUri, "image/*.jpg");
	    		//set crop properties
	    		cropIntent.putExtra("crop", "true");
	    		//indicate aspect of desired crop
	    		cropIntent.putExtra("aspectX", 1);
	    		cropIntent.putExtra("aspectY", 1);
	    		//indicate output X and Y
	    		cropIntent.putExtra("outputX", 10000);
	    		cropIntent.putExtra("outputY", 10000);
	    		//retrieve data on return
	    		cropIntent.putExtra("return-data", true);
	    		//start the activity - we handle returning in onActivityResult
	    		
	    		startActivityForResult(cropIntent, 3);
	    	}

}
